import { Switch, Tooltip, Input, Checkbox, Button } from 'antd';
import type { FC } from 'react';
import { useEffect, useMemo, useState } from 'react';
import styles from './index.less';
import Item from './item';

type ValueType = {
  allowbusywork?: string;
  busywork?: string;
  reward?: any[];
};
interface Props {
  formType?: 'switch' | 'checkbox';
  checkboxText?: string;
  value?: ValueType;
  onChange?: (val: any) => void;
  onOk: (val: any) => void;
}

const REWARD_VALUE_INDEX = {
  B: 1,
  A: 2,
  AA: 3,
  S: 4,
};
const REWARD_COUNT_INDEX = {
  RMB: 1,
  CG券: 2,
};

const Index: FC<Props> = ({
  value,
  onChange,
  onOk,
  formType = 'switch',
  checkboxText = '为该章节设置作业',
}) => {
  const defaultReward = useMemo(
    () => [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
    ],
    [],
  );
  const [visible, setVisible] = useState(false);
  const [checked, setChecked] = useState(false);
  const [demand, setDemand] = useState<string>();
  const [reward, setReward] = useState<any>({});
  const update = (val) => {
    // console.log(val);
    setDemand(val.demand);
    setReward(val.reward);
    if (onChange) {
      const { demand: busywork, reward: _reward } = val;
      const reward = value?.reward?.length ? value?.reward : defaultReward;
      Object.keys(_reward).forEach((key) => {
        if (_reward[key].reward?.length === 2) {
          Object.keys(REWARD_COUNT_INDEX).forEach((k) => {
            if (_reward[key].reward?.[1] === k) {
              reward[REWARD_VALUE_INDEX[key]][REWARD_COUNT_INDEX[k]] = _reward[key].value || 0;
            } else {
              reward[REWARD_VALUE_INDEX[key]][REWARD_COUNT_INDEX[k]] = 0;
            }
          });
        } else {
          reward[REWARD_VALUE_INDEX[key]] = [0, 0, 0];
        }
      });
      onChange({
        busywork,
        reward,
      });
    }
  };
  const onDemandChange = (evt) => {
    update({
      reward,
      demand: evt.target.value,
      checked,
    });
  };
  const onRewardChange = (key, value) => {
    update({
      checked,
      demand,
      reward: {
        ...reward,
        [key]: value,
      },
    });
  };
  const onCancel = () => {
    setChecked(false);
    setVisible(false);
  };
  const onSave = () => {
    setVisible(false);
    setChecked(true);
    const _reward = value?.reward?.length ? value?.reward : defaultReward;
    Object.keys(reward).forEach((key) => {
      if (reward[key].reward?.length === 2) {
        Object.keys(REWARD_COUNT_INDEX).forEach((k) => {
          if (reward[key].reward?.[1] === k) {
            _reward[REWARD_VALUE_INDEX[key]][REWARD_COUNT_INDEX[k]] = reward[key].value || 0;
          } else {
            _reward[REWARD_VALUE_INDEX[key]][REWARD_COUNT_INDEX[k]] = 0;
          }
        });
      } else {
        _reward[REWARD_VALUE_INDEX[key]] = [0, 0, 0];
      }
    });
    console.log(_reward);
    onOk({
      busywork: demand,
      reward: _reward,
      allowbusywork: 1,
    });
  };

  const onCheckedChange = (checked) => {
    if (checked) {
      setVisible(true);
    } else {
      setChecked(false);
      setVisible(false);
      onOk({
        busywork: undefined,
        reward: undefined,
        allowbusywork: 0,
      });
    }
  };

  useEffect(() => {
    setChecked(Boolean(Number(value?.allowbusywork)));
    // console.log(checked, 'checked');
    // console.log(value?.allowbusywork, 'value?.allowbusywork');

    setDemand(value?.busywork);
    const _reward = value?.reward?.length > 0 ? value?.reward : defaultReward;
    const reward = {
      B: {
        reward:
          _reward?.[1]?.[1] !== 0
            ? ['有奖励', 'RMB']
            : _reward?.[1]?.[2] !== 0
            ? ['有奖励', 'CG券']
            : ['无奖励'],
        value: _reward?.[1]?.[1] || _reward?.[1]?.[2],
      },
      A: {
        reward:
          _reward?.[2]?.[1] !== 0
            ? ['有奖励', 'RMB']
            : _reward?.[2]?.[2] !== 0
            ? ['有奖励', 'CG券']
            : ['无奖励'],
        value: _reward?.[2]?.[1] || _reward?.[2]?.[2],
      },
      AA: {
        reward:
          _reward?.[3]?.[1] !== 0
            ? ['有奖励', 'RMB']
            : _reward?.[3]?.[2] !== 0
            ? ['有奖励', 'CG券']
            : ['无奖励'],
        value: _reward?.[3]?.[1] || _reward?.[3]?.[2],
      },
      S: {
        reward:
          _reward?.[4]?.[1] !== 0
            ? ['有奖励', 'RMB']
            : _reward?.[4][2] !== 0
            ? ['有奖励', 'CG券']
            : ['无奖励'],
        value: _reward?.[4]?.[1] || _reward?.[4]?.[2],
      },
    };
    setReward(reward);
  }, [value]);
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
      <Tooltip
        placement="bottom"
        trigger="click"
        visible={visible}
        zIndex={9999}
        onVisibleChange={(vis) => {
          if (!checked && vis) setVisible(vis);
        }}
        overlayClassName="c-tooltip c-input homework-tooltip"
        overlayInnerStyle={{ width: 246, padding: '10px 6px' }}
        title={
          <div className={styles.container}>
            <Input.TextArea
              style={{ resize: 'none', marginBottom: 10 }}
              value={demand}
              onChange={onDemandChange}
              rows={4}
              placeholder="请填写作业要求"
            />
            <Item value={reward?.B} onChange={(value) => onRewardChange('B', value)} text="B" />
            <Item value={reward?.A} onChange={(value) => onRewardChange('A', value)} text="A" />
            <Item value={reward?.AA} onChange={(value) => onRewardChange('AA', value)} text="A+" />
            <Item value={reward?.S} onChange={(value) => onRewardChange('S', value)} text="S" />
            <div style={{ textAlign: 'right' }}>
              <Button
                style={{ width: 66, height: 24, color: '#fff' }}
                type="text"
                onClick={onCancel}
              >
                取消
              </Button>
              <Button style={{ width: 60, height: 24, padding: 0 }} type="primary" onClick={onSave}>
                确定
              </Button>
            </div>
          </div>
        }
      >
        {formType === 'checkbox' ? null : <Switch checked={checked} onChange={onCheckedChange} />}
        {/* {formType === 'checkbox' ? (
          <Checkbox
            checked={checked}
            onChange={(evt) => {
              // setChecked(evt.target.checked);
              const checked = evt.target.checked;
              onCheckedChange(checked);
            }}
          >
            {checkboxText}
          </Checkbox>
        ) : (
          <Switch checked={checked} onChange={onCheckedChange} />
        )} */}
      </Tooltip>
      {checked && (
        <Tooltip
          placement="top"
          overlayClassName="c-tooltip c-input homework-tooltip"
          overlayInnerStyle={{ width: 230, padding: 14 }}
          zIndex={9999}
          title={
            <div>
              {demand && (
                <pre
                  style={{
                    margin: 0,
                    paddingBottom: 12,
                    marginBottom: 12,
                    borderBottom: '1px solid rgba(255,255,255, 0.2)',
                  }}
                >
                  {demand}
                </pre>
              )}
              <div>
                {Object.keys(reward)
                  .reverse()
                  .map((key: string) => {
                    if (!Number(reward[key].value)) {
                      return null;
                    }
                    return (
                      <div>
                        <span>{key === 'AA' ? 'A+' : key}</span>：<span>{reward[key].value}</span>
                        {reward[key].reward[1] === 'RMB' ? 'RM币' : 'CG券额度'}
                      </div>
                    );
                  })}
              </div>
            </div>
          }
        >
          <span className={styles.viewIcon} />
        </Tooltip>
      )}
    </span>
  );
};

export default Index;
